﻿
if (typeof jQuery === "undefined") {
    throw "缺少JQuery组件。(site.js需要在jquery之后载入)";
}
else {
    if (!(typeof jQuery().modal === 'function')) {
        throw "缺少bootStrap组件。";
    }
    if (!jQuery.Toast) {
        console.error("缺少toaster组件。toast相关功能将不能正常使用。");
    }
}


document.onreadystatechange = function (doc, e) {
    if (document.readyState === "interactive") {
        console.log("页面DOM已解析，可进行交互。");
    }
    else if (document.readyState === "complete") {
        console.log("页面资源已加载完成。");
    }
};

var WebApiResult = /** @class */ (function () {
    function WebApiResult(jqxhr) {
        var me = this;
        jqxhr.done.bind(me)(function (result) {
            me.status = result.status;
            me.message = result.message;
            me.data = result.data;
            if (result.status === 1) {
                me.call_done(me);
            }
            else {
                me.call_fail(me);
            }
        });
        jqxhr.fail.bind(me)(function (xhr) {
            //异常状态也转为apiresult
            me.status = -xhr.status;
            me.message = xhr.responseText;
            if (!me.message) {
                if (me.status == 0) {
                    me.message = "网络异常。";
                }
                else if (me.status == -404) {
                    me.message = "请求的目标不存在。";
                }
            }
            me.data = null;
            me.call_fail(me);
        });
        jqxhr.always.bind(me)(function () {
            me.call_always(me);
        });
    }
    WebApiResult.prototype.call_done = function (result) {
        if (this._done) {
            try {
                this._done.forEach(function (element) {
                    element(result);
                });
            }
            catch (error) {
            }
        }
        return this;
    };
    WebApiResult.prototype.call_fail = function (result) {
        if (this._fail) {
            try {
                this._fail.forEach(function (element) {
                    element(result);
                });
            }
            catch (error) {
            }
        }
        return this;
    };
    WebApiResult.prototype.call_always = function (result) {
        if (this._always) {
            try {
                this._always.forEach(function (element) {
                    element(result);
                });
            }
            catch (error) {
            }
        }
        return this;
    };
    WebApiResult.prototype.done = function (callback) {
        if (!this._done) {
            this._done = new Array();
        }
        this._done.push(callback);
        return this;
    };
    WebApiResult.prototype.fail = function (callback) {
        if (!this._fail) {
            this._fail = new Array();
        }
        this._fail.push(callback);
        return this;
    };
    WebApiResult.prototype.always = function (callback) {
        if (!this._always) {
            this._always = new Array();
        }
        this._always.push(callback);
        return this;
    };
    return WebApiResult;
}());
//# sourceMappingURL=WebApiResult.js.map

var HtmlUtil = {
    /**
     * 转为HTML编码
     * @param {string} str HTML字符串
     * @returns {string} 返回编码后的字符串
     */
    htmlEncode: function (str) {
        var s = "";
        if (str.length === 0) return "";
        s = str.replace(/&/g, "&amp;");
        s = s.replace(/</g, "&lt;");
        s = s.replace(/>/g, "&gt;");
        s = s.replace(/ /g, "&nbsp;");
        s = s.replace(/\'/g, "&#39;");
        s = s.replace(/\"/g, "&quot;");
        return s;
    },
    /**
     * HTML解码
     * @param {string} str html编码字符串
     * @returns {string} 返回解码的HTML字符串
     */
    htmlDecode: function (str) {
        var s = "";
        if (str.length === 0) return "";
        s = str.replace(/&amp;/g, "&");
        s = s.replace(/&lt;/g, "<");
        s = s.replace(/&gt;/g, ">");
        s = s.replace(/&nbsp;/g, " ");
        s = s.replace(/&#39;/g, "\'");
        s = s.replace(/&quot;/g, "\"");
        return s;
    }
};

/*JQuery Extension*/
(
    /**
     * 
     * @param {JQuery<HTMLFormElement>} jq JQuery<HTMLFormElement>对象
     */
    function (jq) {
        jq.fn.extend({
            /**
             * 异步提交form的数据
             * @param {Function<number,number>} upProgress 上传进度
            * @param {Function<number, number>} downProgress 下载进度
            * @returns {JQuery.jqXHR} 返回jqXHR对象
             */
            postForm: function (upProgress, downProgress) {
                var form = $(this);

                var url = form.attr("action");
                var formData = new FormData(form[0]);
                return window.postForm(url, formData, upProgress, downProgress);

            },
            /**
             * 重置表单
             * */
            resetForm: function () {
                var form = $(this);
                form[0].reset();

            },
            /**
             * 将对象中的值置入表单
             * @param {any} data json对象
             */
            setForm: function (data) {
                var form = $(this);
                if (!data) {
                    form.resetForm();
                    return;
                } else {
                    for (var i in data) {
                        var tag = form.find("[name='" + i + "']");
                        if (tag.length > 0) {
                            var tagname = tag[0].tagName.toLowerCase();
                            if (tagname === "input") {
                                if (tag.attr("type") === "radio") {
                                    form.find("[name='" + i + "'][value='" + data[i] + "']").atrr("checked", true);
                                }
                                else if (tag.attr("type") === "checkbox") {
                                    form.find("[name='" + i + "'][value='true']").atrr("checked", data[i]);
                                }
                                else {
                                    tag.val(data[i]);
                                }
                            }
                            else if (tagname === "select") {
                                tag.find("option[value='" + data[i] + "']").attr("selected", true);
                            }
                            else {
                                tag.text(data[i]);
                            }
                        }
                    }
                }
            },
            /**
             * 自定义form的提交时的ajax操作并阻止form使用浏览器内置提交功能，调用此方法后表单不会立即提交，需要自行触发表单的提交。
             * @param {Function<JQuery.jqXHR>} jqxhrCallback 指定一个回调，接收参数为jqXHR
             * @param {Function<FormData>} validFunc 表单验证函数，传入要验证的FormData，返回true表示验证成功，返回false表示验证失败，终止表单提交。
             * @param {Function<number,number>} upProgress 上传进度回调
             * @param {Function<number,number>} downProgress 下载进度回调
             */
            onSubmitForm: function (jqxhrCallback, validFunc, upProgress, downProgress) {
                var form = $(this);
                form.on("submit", function () {
                    var formData = new FormData(form[0]);
                    $("form").addClass('was-validated');
                    if (!(form[0].checkValidity()) || (validFunc && !validFunc(formData))) {
                        return false;//验证不成功
                    }
                    var jqxhr = form.postForm(upProgress, downProgress);
                    if (jqxhrCallback) {
                        jqxhrCallback(jqxhr);
                    }
                    return false; //阻止form使用浏览器内置提交功能

                });
            },
            /**
             * 显示加载遮罩层
             * */
            busy: function () {
                var tag = $(this);
                tag.mask("<span class='fa  fa-clock fa-spin'></span>");
            },
            /**
             * 隐藏加载遮罩层
             * */
            unbusy: function () {
                var tag = $(this);
                tag.unmask();
            }


        });
    })(jQuery || JQuery || $);

(function (win) {

    /*标记为ajaxform的表单自动异步提交*/
    $("form[ajaxform]").each(
        function (i, form) {
            $(form).onSubmitForm();
        }
    )

    /**
     * 判断对象是否为指定的类型
     * @param {any} obj 要判断类型的实体
     * @param {string} typeString 类型名称
     * @returns {boolean} 返回true|false
     */
    win.isType = function (obj, typeString) {
        return Object.prototype.toString.call(obj) === '[object ' + typeString + ']';
    };

    /**
     * 将FormData对象转换为JSON对象
     * @param {FormData} formData FormData对象
     * @returns {Object} 返回JSON对象
     */
    win.formToJson = function (formData) {
        var objData = {};

        for (var entry of formData.entries()) {
            objData[entry[0]] = entry[1];
        }
        return objData;
    };

    /**
     * 将json对象提交到webapi
     * @param {string} url 要提交到的url
     * @param {any} data 要提交的json数据
     * @returns {JQuery.jqXHR} 返回jqXHR
     */
    win.postJson = function (url, data) {
        var jqxhr = $.ajax({
            url: url,
            async: true,
            method: 'POST',
            data: JSON.stringify(data),
            dataType: "json",//"xml", "html", "script", "json", "jsonp", "text" 
            contentType: "application/json;charset=UTF-8",
            processData: false,
            cache: false,
            success: function (data) {
            },
            error: function (jqXHR) {
                console.log(JSON.stringify(jqXHR));
            }

        });
        return new WebApiResult(jqxhr);
    };
    /**
     * 将表单数据提交到webapi
     * @param {string} url 要提交到的url
     * @param {any} data 要提交的json|FormData数据
     * @param {Function<number,number>} upProgress 上传数据进度处理
     * @param {Function<number,number>} downProgress 下载数据进度处理 
     * @returns {JQuery.jqXHR} 返回jqXHR数据
     */
    win.postForm = function (url, data, upProgress, downProgress) {
        if (!isType(data, "FormData")) {
            var fd = new FormData();
            for (var k in data) {
                fd.append(k, data[k]);
            }
            data = fd;
        }
        var jqxhr = $.ajax({
            url: url,
            async: true,
            method: 'POST',
            data: data,
            dataType: "json",//"xml", "html", "script", "json", "jsonp", "text"
            contentType: false, // 注意这里应设为false
            processData: false,
            cache: false,
            //complete: function (XHR, TS) {
            //    if (complete) {
            //        complete(XHR, TS);
            //    }

            //},
            xhr: function () {
                var xhr = $.ajaxSettings.xhr();
                xhr.upload.onprogress = function (evt) {
                    if (evt.lengthComputable) {
                        var percentComplete = evt.loaded / evt.total;
                        if (upProgress) {
                            upProgress(evt.loaded, evt.total);
                        }
                    }
                };
                xhr.onprogress = function (evt) {
                    if (evt.lengthComputable) {
                        var percentComplete = evt.loaded / evt.total;
                        if (downProgress) {
                            downProgress(evt.loaded, evt.total);
                        }
                    }
                };
                return xhr;
            }
        });

        return new WebApiResult(jqxhr);
    };

    /**
     * 从webapi获取数据
     * @param {string} url 要请求的url
     * @param {object} paras 请求的参数
     * @param {Function<number,number>} downProgress 下载进度
     * @returns {JQuery.jqXHR} 返回jqXHR对象
     */
    win.httpGet = function (url, paras, downProgress) {

        var jqxhr = $.ajax({
            url: url,
            contentType: "application/x-www-form-urlencoded;charset=utf-8",
            type: 'GET',
            async: true,
            data: paras,
            dataType: 'json',
            cache: false,
            xhr: function () {
                var xhr = $.ajaxSettings.xhr();
                //Download progress
                xhr.onprogress = function (evt) {
                    if (evt.lengthComputable) {
                        var percentComplete = evt.loaded / evt.total;
                        if (downProgress) {
                            downProgress(evt.loaded, evt.total);
                        }
                    }
                };
                return xhr;
            }
        });
        return new WebApiResult(jqxhr);
    };

    win.dlgSuccess = function (title, content, handler) {
        if (!title) {
            title = "";
        }
        if (!content) {
            content = "";
        }
        var str = '<div class="modal fade" tabindex="-1" data-backdrop="static" role="dialog" aria-hidden="true">' +
            '<div class="modal-dialog modal-dialog-centered" role="document">' +
            '<div class="modal-content">' +
            '<div class="modal-header">' +
            '<h5 class="modal-title" style="color:green"><i class="fa fa-check-circle"></i>' + title + '</h5>' +
            '<button type="button" class="close" data-dismiss="modal" aria-label="Close">' +
            '<span aria-hidden="true">&times;</span>' +
            '</button>' +
            '</div>' +
            '<div class="modal-body">' + content +
            '</div>' +
            '<div class="modal-footer">' +
            '<button type="button" class="btn btn-secondary" data-dismiss="modal">关闭</button>' +
            '</div>' +
            '</div>' +
            '</div>' +
            '</div>';

        var dlg = $(str);
        dlg.on("hidden.bs.modal", handler);
        dlg.modal("show");
        return dlg;
    };

    win.dlgError = function (title, content, handler) {
        if (!title) {
            title = "";
        }
        if (!content) {
            content = "";
        }
        var str = '<div class="modal fade" tabindex="-1" data-backdrop="static" role="dialog" aria-hidden="true">' +
            '<div class="modal-dialog modal-dialog-centered" role="document">' +
            '<div class="modal-content">' +
            '<div class="modal-header">' +
            '<h5 class="modal-title" style="color:red"><i class="fa fa-exclamation-circle"></i>' + title + '</h5>' +
            '<button type="button" class="close" data-dismiss="modal" aria-label="Close">' +
            '<span aria-hidden="true">&times;</span>' +
            '</button>' +
            '</div>' +
            '<div class="modal-body">' + content +
            '</div>' +
            '<div class="modal-footer">' +
            '<button type="button" class="btn btn-danger" data-dismiss="modal">关闭</button>' +
            '</div>' +
            '</div>' +
            '</div>' +
            '</div>';
        var dlg = $(str);
        dlg.on("hidden.bs.modal", handler);
        dlg.modal("show");
        return dlg;
    };

    /**
     * 弹出对话框
     * @param {string} title 对话框标题
     * @param {string} content 对话框内容
     * @param {Array<string>} btns 支持的按钮
     * @param {Function<string>} btnclickcallback 按钮回调
     * @returns {JQuery} 返回对话框的JQuery对象
     */
    win.dlg = function (title, content, btns/*ok cancel close yes no*/, btnclickcallback) {
        var btnstr = "";
        var withclose = false;
        if (!btns) {
            btns = ["ok"];
        }
        if ($.inArray('ok', btns) >= 0) {
            btnstr += '<button type="button" class="btn btn-primary" data-btntype="ok">确认</button>';
        }
        if ($.inArray('cancel', btns) >= 0) {
            btnstr += '<button type="button" class="btn btn-default" data-dismiss="modal" data-btntype="cancel">取消</button>';
        }
        if ($.inArray('yes', btns) >= 0) {
            btnstr += '<button type="button" class="btn btn-primary" data-btntype="yes">是</button>';
        }
        if ($.inArray('no', btns) >= 0) {
            btnstr += '<button type="button" class="btn btn-default" data-dismiss="modal" data-btntype="no">否</button>';
        }
        if ($.inArray('close', btns) >= 0) {
            withclose = true;
        }
        var gid = Guid.NewGuid().ToString();
        var template = ('<div class="modal fade" data-backdrop="static" id="' + gid + '" tabindex="-1" role="dialog">'
            + '<div class="modal-dialog modal-dialog-centered" role="document">'
            + '<div class="modal-content">'
            + '<div class="modal-header">'
            + '<h4 class="modal-title">{0}</h4>'
            + (withclose ? '<button type="button" class="close" data-dismiss="modal" aria-label="Close" data-btntype="close"><span aria-hidden="true">&times;</span></button>' : '')
            + '</div>'
            + '<div class="modal-body">'
            + '{1}'
            + '</div>'
            + '<div class="modal-footer">'
            + '{2}'
            + '</div>'
            + '</div>'
            + '</div>'
            + '</div>').format(title, content, btnstr);
        var dialog = $(template);

        dialog.find("button[data-btntype]").on("click", function (event) {
            if (btnclickcallback) {
                var res = btnclickcallback($(this).data("btntype"), dialog, event);
                if (!res) {//返回false则隐藏对话框，返回true则保持对话框
                    dialog.modal("hide");
                }
            }

        });
        dialog.on("hidden.bs.modal", function () {

            dialog.modal("dispose");
            dialog.remove();//动态对话框隐藏后移除该动态生成的元素
        });
        dialog.modal("show");
        return dialog;
    };

    /**
     * 弹出用户输入对话框
     * @param {any} title 标题
     * @param {any} value 默认值
     * @param {Function<string>} onresult 输入结果回调
     */
    win.input = function (title, value, onresult) {
        var val = prompt(title, value);
        if (onresult) {
            onresult(val);
        }
    };

    win.toastError = function (title, msg, closeCallback) {
        $.Toast(title, msg, "error", {
            has_icon: true,
            has_close_btn: true,
            position_class: "toast-top-right",
            fullscreen: true,
            timeout: 3000,
            sticky: false,
            has_progress: true,
            rtl: false
        }, closeCallback);
    };
    win.toastSuccess = function (title, msg, closeCallback) {
        $.Toast(title, msg, "success", {
            has_icon: true,
            has_close_btn: true,
            position_class: "toast-top-right",
            fullscreen: true,
            timeout: 3000,
            sticky: false,
            has_progress: true,
            rtl: false
        }, closeCallback);
    };
    win.toastWaring = function (title, msg, closeCallback) {
        $.Toast(title, msg, "waring", {
            has_icon: true,
            has_close_btn: true,
            position_class: "toast-top-right",
            fullscreen: true,
            timeout: 3000,
            sticky: false,
            has_progress: true,
            rtl: false
        }, closeCallback);
    };
    win.toastInfo = function (title, msg, closeCallback) {
        $.Toast(title, msg, "info", {
            has_icon: true,
            has_close_btn: true,
            position_class: "toast-top-right",
            fullscreen: true,
            timeout: 3000,
            sticky: false,
            has_progress: true,
            rtl: false
        }, closeCallback);
    };

})(window);

/*
 *遮罩层
 */
(function () {
    $.extend($.fn, {
        /*
         *显示遮罩层
         */
        mask: function (content, maskDivClass) {
            this.unmask();
            // 参数
            var op = {
                opacity: 0.5,
                z: 99999,
                bgcolor: '#ccc'
            };
            var original = $(document.body);
            var position = { top: 0, left: 0 };
            if (this[0] && this[0] !== window.document) {
                original = this;
                position = original.position();
            }
            // 创建一个 Mask 层，追加到对象中
            var maskDiv = $('<div class="maskdivgen">&nbsp;</div>');
            maskDiv.appendTo(original);
            var maskWidth = original.outerWidth();
            if (!maskWidth) {
                maskWidth = original.width();
            }
            var maskHeight = original.outerHeight();
            if (!maskHeight) {
                maskHeight = original.height();
            }
            maskDiv.css({
                position: 'absolute',
                top: position.top,
                left: position.left,
                'z-index': op.z,
                width: maskWidth,
                height: maskHeight,
                'background-color': op.bgcolor,
                opacity: 0
            });
            if (maskDivClass) {
                maskDiv.addClass(maskDivClass);
            }
            if (content) {
                var msgDiv = $('<div style="position:absolute;border:#6593cf 1px solid; padding:2px;background:#ccca"><div style="line-height:24px;border:#a3bad9 1px solid;background:white;padding:2px 10px 2px 10px">' + content + '</div></div>');
                msgDiv.appendTo(maskDiv);
                var widthspace = maskDiv.width() - msgDiv.width();
                var heightspace = maskDiv.height() - msgDiv.height();
                msgDiv.css({
                    cursor: 'wait',
                    top: heightspace / 2 - 2,
                    left: widthspace / 2 - 2
                });
            }
            maskDiv.fadeIn('fast', function () {
                // 淡入淡出效果
                $(this).fadeTo('slow', op.opacity);
            });
            return maskDiv;
        },
        /*
         *去除遮罩层
         */
        unmask: function () {
            var original = $(document.body);
            if (this[0] && this[0] !== window.document) {
                original = $(this[0]);
            }
            original.find("> div.maskdivgen").fadeOut('slow', 0, function () {
                $(this).remove();
            });
        }
    });
})();

//GUID 
function Guid(g) {
    var arr = new Array(); //存放32位数值的数组

    if (typeof (g) === "string") { //如果构造函数的参数为字符串 
        InitByString(arr, g);
    }
    else {
        InitByOther(arr);
    }
    //返回一个值，该值指示 Guid 的两个实例是否表示同一个值。 
    this.Equals = function (o) {
        if (o && o.IsGuid) {
            return this.ToString() === o.ToString();
        }
        else {
            return false;
        }
    };

    //Guid对象的标记 
    this.IsGuid = function () { }
    //返回 Guid 类的此实例值的 String 表示形式。 
    this.ToString = function (format) {
        if (typeof (format) === "string") {
            if (format === "N" || format === "D" || format === "B" || format === "P") {
                return ToStringWithFormat(arr, format);
            }
            else {
                return ToStringWithFormat(arr, "D");
            }
        }
        else {
            return ToStringWithFormat(arr, "D");
        }
    };
    this.toString = function (format) {
        return this.ToString(format);
    };
    //由字符串加载 
    function InitByString(arr, g) {
        g = g.replace(/\{|\(|\)|\}|-/g, "");
        g = g.toLowerCase();
        if (g.length !== 32 || g.search(/[^0-9,a-f]/i) !== -1) {
            InitByOther(arr);
        }
        else {
            for (var i = 0; i < g.length; i++) {
                arr.push(g[i]);
            }
        }
    }
    //由其他类型加载 
    function InitByOther(arr) {
        var i = 32;
        while (i--) {
            arr.push("0");
        }
    }

    /*
 
    根据所提供的格式说明符，返回此 Guid 实例值的 String 表示形式。
 
    N  32 位： xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
 
    D  由连字符分隔的 32 位数字 xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
 
    B  括在大括号中、由连字符分隔的 32 位数字：{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}
 
    P  括在圆括号中、由连字符分隔的 32 位数字：(xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx)
 
    */

    function ToStringWithFormat(arr, format) {
        var str;
        switch (format) {
            case "N":
                return arr.toString().replace(/,/g, "");
            case "D":
                str = arr.slice(0, 8) + "-" + arr.slice(8, 12) + "-" + arr.slice(12, 16) + "-" + arr.slice(16, 20) + "-" + arr.slice(20, 32);
                str = str.replace(/,/g, "");
                return str;
            case "B":
                str = ToStringWithFormat(arr, "D");
                str = "{" + str + "}";
                return str;
            case "P":
                str = ToStringWithFormat(arr, "D");
                str = "(" + str + ")";
                return str;
            default:
                return new Guid();
        }
    }
}
//Guid 类的默认实例，其值保证均为零。 
Guid.Empty = new Guid();
//初始化 Guid 类的一个新实例。 
Guid.NewGuid = function () {
    var g = "";
    var i = 32;
    while (i--) {
        g += Math.floor(Math.random() * 16.0).toString(16);
    }
    return new Guid(g);
};

//格式化字符串
String.prototype["format"] = function (args) {
    var result = this;
    if (arguments.length > 0) {
        if (arguments.length === 1 && typeof args === "object") {
            for (var key in args) {
                if (args[key] !== undefined) {
                    var regexp = new RegExp("({" + key + "})", "g");
                    var value = args[key];
                    if (value === null) {
                        value = "";
                    }
                    result = result.replace(regexp, value);
                }
            }
        }
        else {
            for (var i = 0; i < arguments.length; i++) {
                if (arguments[i] !== undefined) {
                    var reg_exp = new RegExp("({[" + i + "]})", "g");

                    result = result.replace(reg_exp, arguments[i]);
                }
            }
        }
    }
    return result;
};

// 对Date的扩展，将 Date 转化为指定格式的String 
// 月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符， 
// 年(y)可以用 1-4 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字) 
// 例子： 
// (new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423 
// (new Date()).Format("yyyy-M-d h:m:s.S")      ==> 2006-7-2 8:9:4.18 
Date.prototype["Format"] = function (fmt) { //author: meizz 
    var o = {
        "M+": this.getMonth() + 1,                 //月份 
        "d+": this.getDate(),                    //日 
        "h+": this.getHours(),                   //小时 
        "m+": this.getMinutes(),                 //分 
        "s+": this.getSeconds(),                 //秒 
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度 
        "S": this.getMilliseconds()             //毫秒 
    };
    if (/(y+)/.test(fmt))
        fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt))
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
};

String.prototype.startWith = function (str) {
    var reg = new RegExp("^" + str);
    return reg.test(this);
};

String.prototype.endWith = function (str) {
    var reg = new RegExp(str + "$");
    return reg.test(this);
};
